package newNetty;

import com.alibaba.fastjson.JSONArray;
import config.MessageBo;
import config.MyResult;
import config.UserInfoBO;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;



import static config.Constants.mapUser;
import static config.Constants.ports;
import static config.Constants.userIdAddress;

/**
 * @author : GuoFei
 * @date : 2018/11/19 11:13
 */
@Service
public class WebScoketService {



    @Autowired
    private WebSocketServer webSocketServer;

    public MyResult getAllUser() {
        System.out.println(mapUser.values());
        System.out.println(userIdAddress.values());
        return MyResult.success(mapUser.values());
    }

    public MyResult begin(int port) {
        if (ports.contains(port)) {
            return MyResult.success();
        } else {
            ports.add(port);
        }
        webSocketServer.run(port);
        return MyResult.success();
    }

    public MyResult end() {
        webSocketServer.end(2006);
        return MyResult.success();
    }

    public MyResult sendAll(MessageBo messageBo ) {
        if (messageBo.getType() != 4) {
            return MyResult.error();
        } else {
            for (UserInfoBO user : mapUser.values()) {
                sendMessageToOne(user.getId(),messageBo.getMessage());
            }
            return MyResult.success();
        }
    }

    public MyResult sendOne() {
        return MyResult.success();
    }

    public MyResult replyOne(MessageBo messageBo) {
        sendMessageToOne(messageBo.getId(),messageBo.getMessage());
        return MyResult.success();
    }

    public MyResult addUser() {
        return MyResult.success();
    }

    public MyResult delUser() {
        return MyResult.success();
    }

    public void sendMessageToOne(int id,String message){
        UserInfoBO userInfoBO = mapUser.get(String.valueOf(id));
        userInfoBO.getCtx().writeAndFlush(new TextWebSocketFrame(message));
    }
}
